# _*_ coding:utf-8 _*_
# @Time  : 2022.10.27
# @Author: zizlee
from fastapi import APIRouter, Body, Header, Query
from pydantic import BaseModel
from hutool import security
from v1_all_api.all_response import AllResponse
from db import FAConnection

group_api = APIRouter()


class GroupItem(BaseModel):
    id: int = 0
    name: str
    variety_en: str
    group_type: str


@group_api.post('/')  # 新建一个分类
def create_datalib_group(ruizy_token: str = Header(...), group: GroupItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    print(group)
    db_conn = FAConnection()
    if group.id < 1:  # 新建
        sql = "INSERT INTO datalib_variety_group (name,group_type,variety_en,user_id) VALUES (%s,%s,%s,%s);"
        prm = (group.name, group.group_type, group.variety_en, person['uid'])
        success, _ = db_conn.insert(sql, prm)
        message = '新建组别成功!'
    else:  # 修改
        sql = 'UPDATE datalib_variety_group SET name=%s WHERE id=%s LIMIT 1;'
        prm = (group.name, group.id)
        _, success = db_conn.execute(sql, prm)
        message = '修改组别成功!'
    return AllResponse.operate_successfully(msg=message) if success else AllResponse.server_error()


@group_api.delete('/')
def delete_datalib_group(ruizy_token: str = Header(...), group: GroupItem = Body(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    # 查询这个id下的group信息
    db_conn = FAConnection()
    g_obj = db_conn.query('SELECT id,user_id FROM datalib_variety_group WHERE id=%s LIMIT 1;', [group.id],
                          keep_conn=True, fetchone=True)[0]
    if not g_obj:
        db_conn.close()
        return AllResponse.validate_error(msg='组别不存在!')
    if person['uid'] != g_obj['user_id']:
        db_conn.close()
        return AllResponse.validate_error(msg='请不要操作他人设置的分组!')

    # 查询这个分组下是否有数据
    if group.group_type == 'chart':
        exist_sql = 'SELECT id FROM datalib_variety_chart WHERE group_id=%s LIMIT 1;'
    elif group.group_type == 'sheet':
        exist_sql = 'SELECT id FROM datalib_variety_sheet WHERE group_id=%s LIMIT 1;'
    else:
        db_conn.close()
        return AllResponse.validate_error(msg='请求参数错误!')
    exist_data = db_conn.query(exist_sql, param=[group.id], fetchone=True, keep_conn=True)[0]
    if exist_data:
        db_conn.close()
        return AllResponse.validate_error(msg='分组下有数据,请放弃这个操作!')
    # 删除分组
    _, success = db_conn.execute('DELETE FROM datalib_variety_group WHERE id=%s LIMIT 1;', param=[group.id])
    return AllResponse.operate_successfully(msg='删除分组成功!') if success else AllResponse.server_error()


@group_api.get('/')  # 查询分类
def query_datalib_group(ruizy_token: str = Header(...), v: str = Query(...), t: str = Query(...)):
    person = security.decrypt_access_token(ruizy_token)
    if not person:
        return AllResponse.no_authorization()
    # 将数据入库
    db_conn = FAConnection()

    sql = """
      SELECT id,name,group_type,variety_en 
      FROM datalib_variety_group WHERE user_id=%s AND variety_en=%s AND group_type=%s 
      ORDER BY sorted;
    """
    prm = (person['uid'], v, t)
    records = db_conn.query(sql, prm)
    records.insert(0, {
        'id': 0,
        'name': '默认组',
        'group_type': t,
        'variety_en': v
    })
    return AllResponse.operate_successfully(data=records)

